package net.ebakker.sheets;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public final class SheetDownloader {
	private static final String SHEETMAKER_LOCATION = "/opt/sheetmaker/smlcli.pl";

	private SheetDownloader() {
		// prevent instantiation
	}

	public static void createSheets(List<File> resultingFiles, String template) {
		getSheets(resultingFiles, template);
		createXml(resultingFiles);
	}

	private static void getSheets(List<File> resultingFiles, String template) {
		File listFile = new File("templist");
		try {
			listFile.createNewFile();
			FileWriter writer = new FileWriter(listFile);
			for (File episode : resultingFiles) {
				writer.write(episode.getAbsolutePath() + "\n");
			}
			writer.flush();
			writer.close();
			String command =
					SHEETMAKER_LOCATION + " " + template + " " + listFile.getAbsolutePath();
			System.out.println("Executing: " + command + " ...");
			Process p = Runtime.getRuntime().exec(command);
			p.waitFor();
			listFile.delete();
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static void createXml(List<File> resultingFiles) {
		try {
			for (File episode : resultingFiles) {
				String path = episode.getAbsolutePath();
				String nfoPath = path.replace(".mkv", ".xml");
				FileWriter writer = new FileWriter(nfoPath);
				writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
						+ "<details>\n\t<backdrop>");
				writer.write(episode.getName() + "_sheet.jpg");
				writer.write("</backdrop>\n" + "</details>");
				writer.flush();
				writer.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
